import logging
import unittest

from api.goods_api import GoodsAPI
from common.db_util import DBUtil
import config.db_cnf as db_cnf
import config.params_cnf as params_cnf


class TestGoods(unittest.TestCase):
    dbUtil = None

    @classmethod
    def setUp(cls) -> None:
        cls.dbUtil = DBUtil(host=db_cnf.host, port=db_cnf.port,
                            user=db_cnf.user, password=db_cnf.password,
                            database=db_cnf.database)

    def test_get_category(self):
        print('获取商品分类')

        resp = GoodsAPI().get_category()
        self.assertEqual(200, resp.status_code)

        # 预期结果：数据库category表中商品分类的个数
        sql = "SELECT count(*) FROM category"
        db_data = self.dbUtil.dql_one(sql)[0]
        logging.info(db_data)

        self.assertEqual(db_data, len(resp.json()))

    def test_product_by_category(self):
        print('获取商品分类下的商品')

        resp = GoodsAPI().get_prod_by_category(params_cnf.CATEGORY_ID)
        self.assertEqual(200, resp.status_code)

        # 预期结果：category_id下的商品个数
        sql = f"SELECT count(*) FROM product WHERE category_id = '{params_cnf.CATEGORY_ID}'"
        db_data = self.dbUtil.dql_one(sql)[0]
        logging.info(db_data)

        # 断言商品分类下的商品数量
        self.assertEqual(db_data, len(resp.json()))

    def test_product_info(self):
        print('获取商品信息')

        resp = GoodsAPI().get_product_info(params_cnf.PRODUCT_ID)
        self.assertEqual(200, resp.status_code)

        # 预期结果：数据库中商品的信息
        sql = f"SELECT * FROM product WHERE id = '{params_cnf.PRODUCT_ID}'"
        db_data = self.dbUtil.dql_one(sql)[1]
        logging.info(db_data)

        resp_name = resp.json().get('name')
        self.assertEqual(db_data, resp_name)
